package com.fujin.gulimall.cart.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fujin.common.utils.R;
import com.fujin.gulimall.cart.Interceptor.CartInterceptor;
import com.fujin.gulimall.cart.config.MyThreadPollConfig;
import com.fujin.gulimall.cart.feign.ProductFeign;
import com.fujin.gulimall.cart.service.CartService;
import com.fujin.gulimall.cart.vo.CartItemVo;
import com.fujin.gulimall.cart.vo.CartVo;
import com.fujin.gulimall.cart.vo.SkuInfoVo;
import com.fujin.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @title: webController
 * @Author uIn
 * @Date: 2022/3/10 22:09
 * @Version 1.0
 */
@Controller
public class webController {

    @Autowired
    private CartService cartService;

    /**
     * 去购物车页面的请求【未登录状态也可以查看】
     * 浏览器有一个cookie:user-key 标识用户的身份，一个月过期
     * 如果第一次使用jd的购物车功能，都会给一个临时的用户身份:
     * 浏览器以后保存，每次访问都会带上这个cookie；
     *
     * 登录：session有
     * 没登录：按照cookie里面带来user-key来做
     * 第一次，如果没有临时用户，自动创建一个临时用户
     */
    @GetMapping("/cartList.html")
    public String cartList(Model model) throws ExecutionException, InterruptedException {
        //获取购物车内容
        CartVo cartVo = cartService.getCart();
        model.addAttribute("cart",cartVo);
        return "cartList.html";
    }

    @GetMapping("/success.html")
    public String success(){
        return "success.html";
    }

    /**
     * 添加商品到购物车
     * @param skuId
     * @param num
     * @return
     */
    public String addCart(@RequestParam("skuId") Long skuId,
                          @RequestParam("num")Integer num,
                          RedirectAttributes attributes) throws ExecutionException, InterruptedException {

        CartItemVo cartItemVo = cartService.addCart(skuId,num);
        attributes.addAttribute("skuId", skuId);// 给重定向请求用的【参数会拼接在下面请求之后】【转发会在请求域中】
        return "redirect:http://localhost:30000/addToCartSuccessPage.html";
    }

    /**
     * 跳转到添加购物车成功页面【防止重复提交】
     */
    @GetMapping(value = "/addToCartSuccessPage.html")
    public String addToCartSuccessPage(@RequestParam("skuId") Long skuId,
                                       Model model) {
        //重定向到成功页面。再次查询购物车数据即可
        CartItemVo cartItemVo = cartService.getCartItem(skuId);
        model.addAttribute("cartItem",cartItemVo);
        return "success";
    }

}
